package com.tmt.im.manager.service;

import com.tmt.im.common.enums.IMAuthorityEnum;
import com.tmt.im.common.pojo.*;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.util.CollectionUtils;

import javax.cache.integration.CompletionListener;
import java.security.Principal;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/12 16:02
 * @Version 1.0
 **/
public class BaseService {

    protected final Ignite ignite;

    protected final IgniteCache<Long, IMUserPoJo> userCache;

    protected final IgniteCache<Long, PersonalSettingPoJo> settingCache;

    protected final IgniteCache<BlackBillKey, BlackBillPoJo> blackBillCache;

    protected final IgniteCache<IMFriendKey, IMFriendPoJo> friendCache;

    protected final IgniteCache<Long, IMFriendGroupPoJo> friendGroupCache;

    protected final IgniteCache<Long, IMFriendApplyPoJo> friendApplyCache;

    protected final IgniteCache<Long, IMFriendGroupMappingPoJo> groupMappingCache;

    public BaseService(Ignite ignite) {
        this.ignite = ignite;
        userCache = ignite.cache(IMUserPoJo.CACHE_NAME);
        settingCache = ignite.cache(PersonalSettingPoJo.CACHE_NAME);
        blackBillCache = ignite.cache(BlackBillPoJo.CACHE_NAME);
        friendCache = ignite.cache(IMFriendPoJo.CACHE_NAME);
        friendGroupCache = ignite.cache(IMFriendGroupPoJo.CACHE_NAME);
        friendApplyCache = ignite.cache(IMFriendApplyPoJo.CACHE_NAME);
        groupMappingCache = ignite.cache(IMFriendGroupMappingPoJo.CACHE_NAME);
    }

    /**
     * 是否有足够权限。
     *
     * @param principal
     * @param authorityEnums
     * @return
     */
    public boolean hasAuthenticated(Principal principal, List<IMAuthorityEnum> authorityEnums) {
        if (principal instanceof JwtAuthenticationToken token) {
            //查询是否具备权限
            List<String> authorities = token.getToken().getClaim("authorities");
            return !CollectionUtils.isEmpty(authorityEnums)
                    && authorityEnums.stream().anyMatch(x -> authorities.contains(x.name()));
        }
        return false;
    }

}
